import request from '../request'
import { API_ENDPOINTS } from '../config'

// 用户信息接口
export interface User {
  id: number
  username: string
  email: string
  name: string
  avatar?: string
  role: 'admin' | 'manager' | 'user'
  permissions: string[]
  lastLoginTime: string
  createdAt: string
}

// 登录参数
export interface LoginParams {
  username: string
  password: string
  remember?: boolean
  captcha?: string
}

// 登录响应
export interface LoginResponse {
  user: User
  token: string
  refreshToken: string
  expiresIn: number
}

// 认证 API 服务
export const authApi = {
  // 用户登录
  login(params: LoginParams) {
    return request.post<LoginResponse>(API_ENDPOINTS.USER.LOGIN, params)
  },

  // 用户登出
  logout() {
    return request.post(API_ENDPOINTS.USER.LOGOUT)
  },

  // 获取用户信息
  getUserProfile() {
    return request.get<User>(API_ENDPOINTS.USER.PROFILE)
  },

  // 更新用户信息
  updateProfile(data: Partial<Pick<User, 'name' | 'email' | 'avatar'>>) {
    return request.put<User>(API_ENDPOINTS.USER.PROFILE, data)
  },

  // 修改密码
  changePassword(data: {
    oldPassword: string
    newPassword: string
    confirmPassword: string
  }) {
    return request.post('/user/change-password', data)
  },

  // 刷新 token
  refreshToken(refreshToken: string) {
    return request.post<{
      token: string
      refreshToken: string
      expiresIn: number
    }>('/auth/refresh', { refreshToken })
  },

  // 获取验证码
  getCaptcha() {
    return request.get<{
      captchaId: string
      captchaImage: string
    }>('/auth/captcha')
  },

  // 忘记密码
  forgotPassword(email: string) {
    return request.post('/auth/forgot-password', { email })
  },

  // 重置密码
  resetPassword(data: {
    token: string
    newPassword: string
    confirmPassword: string
  }) {
    return request.post('/auth/reset-password', data)
  },
}